// 用户模块
import { userAccountLogin, userMobileLogin, userQQBindLogin, userQQPatchLogin } from '@/api/user'
export default {
  namespaced: true,
  state () {
    return {
      // 用户信息
      profile: {
        id: '',
        avatar: '',
        nickname: '',
        account: '',
        mobile: '',
        token: ''
      }
    }
  },
  mutations: {
    // 修改用户信息，payload就是用户信息对象
    setUser (state, payload) {
      state.profile = payload
    }
  },
  actions: {
    // 账号登录获取用户信息
    async userAccountLogin (context, accountInfo) {
      // 发送ajax
      try {
        const data = await userAccountLogin({ account: accountInfo.account, password: accountInfo.password })
        context.commit('setUser', data.result)
      } catch (err) {
        const msg = err.response.data.message
        throw new Error(msg)
      }
    },
    // 手机号登录
    async userMobileLogin (context, accountInfo) {
      // 发送ajax
      try {
        const data = await userMobileLogin({ mobile: accountInfo.mobile, code: accountInfo.code })
        context.commit('setUser', data.result)
      } catch (err) {
        const msg = err.response.data.message
        throw new Error(msg)
      }
    },
    // QQ绑定手机号登录
    async userQQBindLogin (context, accountInfo) {
      // 发送ajax
      try {
        const data = await userQQBindLogin(accountInfo)
        context.commit('setUser', data.result)
      } catch (err) {
        const msg = err.response.data.message || '绑定失败'
        throw new Error(msg)
      }
    },
    // QQ绑定注册账号
    async userQQPatchLogin (context, {
      unionId,
      mobile,
      account,
      password,
      code
    }) {
      // 发送ajax
      try {
        const data = await userQQPatchLogin({
          unionId,
          mobile,
          account,
          password,
          code
        })
        context.commit('setUser', data.result)
      } catch (err) {
        const msg = err.response.data.message
        throw new Error(msg)
      }
    }
  }
}
